<template>
  <div class="home">
    <div class="container">
      <el-form :inline="true" :model="form" :rules="rules" ref="form" class="form" label-width="120px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="save">添加</el-button>

    </div>
  </div>
</template>

<script>

export default {
  name: 'AddAdmin',
  data() {
    const checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'));
      }
      if (!/[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(value)) {
        callback(new Error('请输入合法的邮箱格式'));
      }
      callback();
    };

    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
      if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(value)) {
        callback(new Error('请输入合法的手机号'));
      }
      callback();
    };
    return {
      form: {},
      rules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { validator: checkPhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
      }
    }
  },
  methods: {
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.request.post("/api/admin/save", this.form).then(res => {
            if (res.code === '200') {
              this.$notify.success("添加成功");
            } else {
              this.$notify.error(res.msg);
            }
            this.form = {};
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>


<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;

  .container {
    width: 800px;
    height: 500px;

    margin-top: 80px;
    background-color: #ffffff;
    border-radius: 25px;
    box-shadow: 0 3px 5px #ccc;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;

    .form {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
  }
}
</style>